import React, { createContext, useContext, useState, useEffect } from "react";
import { message, Modal } from "antd";

// 创建主题上下文
const ThemeContext = createContext();

// 主题提供者组件
export const ThemeProvider = ({ children }) => {
  const [isDarkMode, setIsDarkMode] = useState(() => {
    const savedTheme = localStorage.getItem("theme");
    // 如果用户之前没有设置过主题，默认使用深色模式
    if (savedTheme === null) {
      localStorage.setItem("theme", "dark");
      return true;
    }
    return savedTheme === "dark";
  });

  const toggleDarkMode = () => {
    const newTheme = !isDarkMode;
    setIsDarkMode(newTheme);
    localStorage.setItem("theme", newTheme ? "dark" : "light");
  };

  // 当主题改变时，更新全局的 message 和 Modal 样式
  useEffect(() => {
    if (isDarkMode) {
      // 深色模式
      message.config({
        top: 24,
      });
      Modal.config({
        maskClosable: false,
      });
      // 设置全局CSS变量用于深色模式
      document.documentElement.style.setProperty("--theme-bg", "#141414");
      document.documentElement.style.setProperty("--theme-text", "#ffffff");
      document.documentElement.style.setProperty("color-scheme", "dark");
      document.documentElement.classList.add("dark-mode");
      document.documentElement.classList.remove("light-mode");
      document.body.classList.add("dark-mode");
      document.body.classList.remove("light-mode");
    } else {
      // 浅色模式
      message.config({
        top: 24,
      });
      Modal.config({
        maskClosable: false,
      });
      // 设置全局CSS变量用于浅色模式
      document.documentElement.style.setProperty("--theme-bg", "#ffffff");
      document.documentElement.style.setProperty("--theme-text", "#000000");
      document.documentElement.style.setProperty("color-scheme", "light");
      document.documentElement.classList.add("light-mode");
      document.documentElement.classList.remove("dark-mode");
      document.body.classList.add("light-mode");
      document.body.classList.remove("dark-mode");
    }
  }, [isDarkMode]);

  return (
    <ThemeContext.Provider value={{ isDarkMode, toggleDarkMode }}>
      {children}
    </ThemeContext.Provider>
  );
};

// 自定义Hook来使用主题
export const useTheme = () => {
  const context = useContext(ThemeContext);
  if (!context) {
    throw new Error("useTheme must be used within a ThemeProvider");
  }
  return context;
};
